package com.ciwong.epaper.modules.epaper.adapter;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.FollowreadTextParagraph;
import com.ciwong.epaper.modules.epaper.bean.FollowreadTextParagraphBean;
import com.ciwong.epaper.modules.epaper.bean.Sentences;
import com.ciwong.epaper.modules.epaper.ui.ChooseSentenceActivity;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:句子选择适配器
 * @author: wyk
 * @time: 2021/5/19 17:46
 */
public class ChooseSentenceAdapter extends BaseAdapter {

    private Context mContext;
    private FollowreadTextParagraphBean followreadTextParagraphBean;
    //是否是手动暂停
    private boolean isPause = false;

    private ImageView word_audios_img_fake;
    //正在播放或上一个播放的音频versionId
    private String oldVersionId;
    //正在播放或上一个播放的音频url
    private String oldAudioUrl;
    //当前选择的句子集合
    private List<Sentences> mSentenceList = new ArrayList<>();
    //音频播放索引
    private int audioPlayIndex;

    // 单词播放时长 用于录音与结束录音
    protected long audioPlayDuration;
    //当前播放的句子
    protected Sentences curSentence;

    protected Handler mHandler = new Handler();

    public ChooseSentenceAdapter(Context mContext, FollowreadTextParagraphBean followreadTextParagraphBean) {
        this.mContext = mContext;
        this.followreadTextParagraphBean = followreadTextParagraphBean;
    }

    @Override
    public int getCount() {
        return null == followreadTextParagraphBean.getFollowReadWordDetailsList() ? 0 : followreadTextParagraphBean.getFollowReadWordDetailsList().size();
    }

    @Override
    public Object getItem(int i) {
        return null == followreadTextParagraphBean.getFollowReadWordDetailsList() ? 0 : followreadTextParagraphBean.getFollowReadWordDetailsList();
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (null == view) {
            view = LayoutInflater.from(mContext).inflate(R.layout.activity_choose_sentence_list_item, viewGroup, false);
            viewHolder = new ViewHolder();
            viewHolder.choose_sentence_work_content = view.findViewById(R.id.choose_sentence_work_content);
            viewHolder.choose_senten_name_text = view.findViewById(R.id.choose_senten_name_text);
            viewHolder.word_audios_img = view.findViewById(R.id.word_audios_img);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        final List<FollowreadTextParagraph> followreadTextParagraphList = followreadTextParagraphBean.getFollowReadWordDetailsList();
        //设置完整句子
        viewHolder.choose_senten_name_text.setText(followreadTextParagraphList.get(i).getContent());
        int sentenceCount = followreadTextParagraphList.size();
        if (followreadTextParagraphBean.getCheckCount() == sentenceCount) {
            viewHolder.choose_sentence_work_content.setChecked(true);
        } else if (followreadTextParagraphBean.getCheckCount() == 0) {
            viewHolder.choose_sentence_work_content.setChecked(false);
        } else {
            if (null != followreadTextParagraphList.get(i).getChecked() && followreadTextParagraphList.get(i).getChecked()) {
                viewHolder.choose_sentence_work_content.setChecked(true);
            } else {
                viewHolder.choose_sentence_work_content.setChecked(false);
            }
        }

        /*else {
            if (null == followreadTextParagraphList.get(i).getChecked() || followreadTextParagraphList.get(i).getChecked()) {
                viewHolder.choose_sentence_work_content.setChecked(true);
            } else {
                viewHolder.choose_sentence_work_content.setChecked(false);
            }
        }*/

        viewHolder.choose_sentence_work_content.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!compoundButton.isPressed()) {
                    return;
                }
                if (b) {
                    viewHolder.choose_sentence_work_content.setChecked(true);
                    followreadTextParagraphList.get(i).setChecked(true);
                    followreadTextParagraphBean.setCheckCount(followreadTextParagraphBean.getCheckCount() + 1);
                    if (mContext instanceof ChooseSentenceActivity) {
                        ((ChooseSentenceActivity) mContext).setCheckStatus();
                    }
                } else {
                    viewHolder.choose_sentence_work_content.setChecked(false);
                    followreadTextParagraphList.get(i).setChecked(false);
                    followreadTextParagraphBean.setCheckCount(followreadTextParagraphBean.getCheckCount() - 1);
                    if (mContext instanceof ChooseSentenceActivity) {
                        ((ChooseSentenceActivity) mContext).setCheckStatus();
                    }
                }
            }
        });

        viewHolder.word_audios_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // AudioPlayer.getInstance().play(dkWorkDetail.getAudios(),null);
                mSentenceList = followreadTextParagraphList.get(i).getSentences();
                if (AudioPlayer.getInstance().isPlaying()) {
                    //（有versionId则判断versionId 没有则判断url）
                    if (null != oldVersionId && !"".equals(oldVersionId) && mSentenceList.size() > audioPlayIndex && null != mSentenceList.get(audioPlayIndex).getVersionId()) {
                        //判断是否点击的是不是正在播放的句子 是则直接停止 不是则 停止播放当前正在播放的句子 播放新点击的句子
                        if (oldVersionId.equals(mSentenceList.get(audioPlayIndex).getVersionId())) {
                            stopPlaySentence();
                        } else {
                            stopPlaySentence();
                            startPlaySentence(viewHolder.word_audios_img, mSentenceList.get(audioPlayIndex));
                            //startPlay(word_audios_img, mSentenceList.get(audioPlayIndex).getAudioUrl(), mSentenceList.get(audioPlayIndex).getVersionId());
                        }
                    } else {
                        if (mSentenceList.size() > audioPlayIndex && oldAudioUrl.equals(mSentenceList.get(audioPlayIndex).getAudioUrl())) {
                            stopPlaySentence();
                        } else {
                            stopPlaySentence();
                            startPlaySentence(viewHolder.word_audios_img, mSentenceList.get(audioPlayIndex));
                            //startPlay(word_audios_img, mSentenceList.get(audioPlayIndex).getAudioUrl(), mSentenceList.get(audioPlayIndex).getVersionId());
                        }
                    }

                } else {
                    audioPlayIndex = 0;
                    startPlaySentence(viewHolder.word_audios_img, mSentenceList.get(audioPlayIndex));
                    //startPlay(word_audios_img, mSentenceList.get(audioPlayIndex).getAudioUrl(), mSentenceList.get(audioPlayIndex).getVersionId());
                }
            }

        });

        return view;
    }

    /**
     * 停止播放音频
     */
    public void stopPlaySentence() {
        Log.e("MediaPlayer ", "停止播放");
        audioPlayIndex = 0;
        isPause = true;
        AudioPlayer.getInstance().stop();
        if (null != word_audios_img_fake) {
            stopPlayAnimation(word_audios_img_fake);
        }
    }


    /**
     * 开始播放句子音频
     */
    public void startPlaySentence(ImageView word_audios_img, Sentences sentence) {
        startPlayAnimation(word_audios_img);
        String url = "";
        if (null != sentence.getAudioUrl()) {
            url = sentence.getAudioUrl();
        }

        curSentence = sentence;
        word_audios_img_fake = word_audios_img;
        oldVersionId = sentence.getVersionId();
        oldAudioUrl = sentence.getAudioUrl();
        int start = 0;
        int duration = 0;
        if (null != sentence.getStart() && !"".equals(sentence.getStart())) {
            start = Integer.parseInt(sentence.getStart().trim());
        }
        if (null != sentence.getDuration() && !"".equals(sentence.getDuration())) {
            duration = Integer.parseInt(sentence.getDuration().trim());
        }
        if (start > 0 || duration > 0) {
            AudioPlayer.getInstance().setOnPlayListener(listener).play(url,
                    true, start, (duration + start));
            getPlayTime(duration, url);
        } else {
            AudioPlayer.getInstance().setOnPlayListener(listener).play(url,
                    true);
        }
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M
                    && EApplication.getInstance().mPlayerspeed != 1.0f) {
                MediaPlayer mMediaPlayer = AudioPlayer.getInstance()
                        .getMediaPlayer();
                if (mMediaPlayer != null) {
                    try {
                        PlaybackParams params = mMediaPlayer.getPlaybackParams()
                                .setSpeed(EApplication
                                        .getInstance().mPlayerspeed);
                        if (params != null) {
                            mMediaPlayer.setPlaybackParams(params);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取播放时间
     */
    protected void getPlayTime(long duration, Object mp3) {
        // 获取播放单词时长
        if (!"pcm".equals(mp3 + "")) {
            if (duration <= 0) {
                audioPlayDuration = 10000;
            } else {
                long subDuration = (long) (duration * 0.5);
                audioPlayDuration = duration;
            }
        }
    }

    // 播放控制器的监听 包括句子播放完成的后续操作
    protected OnPlayListener listener = new OnPlayListener() {

        @Override
        public void stop(final Object mp3) {
            if (!isPause) {
                audioPlayIndex++;
                if (mSentenceList.size() > audioPlayIndex) {
                    startPlaySentence(word_audios_img_fake, mSentenceList.get(audioPlayIndex));
                } else {
                    audioPlayIndex = 0;
                    Log.e("MediaPlayer ", "停止播放");
                    stopPlayAnimation(word_audios_img_fake);
                }
            }
            isPause = false;

        }

        @Override
        public void onReadPlayer(long duration, Object mp3) {
            long curDuration = duration;
            long transitDuration = 0;
            if (null != curSentence.getDuration() && !"".equals(curSentence.getDuration())) {
                transitDuration = Long.parseLong(curSentence.getDuration().trim());
            }
            if (curSentence != null && transitDuration > 0) {
                curDuration = transitDuration;
            }
            getPlayTime(curDuration, mp3);
        }

        @Override
        public void onPlayStart(Object o) {

        }

        @Override
        public void onPlaying(long duration, long progressSource) {

        }

        @Override
        public void onBuffer(Object o, long l, long l1) {

        }

        @Override
        public void onError(int i, Object tag) {
            audioPlayIndex = 0;
            ToastUtil.INSTANCE.toastCenterError(mContext.getString(R.string.play_audio_faild));
            AudioPlayer.getInstance().stop();
            stopPlayAnimation(word_audios_img_fake);
        }
    };


    /**
     * 开始播放动画
     */
    private void startPlayAnimation(ImageView imageView) {
        imageView
                .setImageResource(R.drawable.dk_bg_annimation);

        final AnimationDrawable animationDrawable = (AnimationDrawable) imageView
                .getDrawable();
        animationDrawable.start();
    }

    /**
     * 停止播放动画
     */
    public void stopPlayAnimation(ImageView word_audios_img) {
        Drawable drawable = word_audios_img.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            ((AnimationDrawable) drawable).stop();
        }
        word_audios_img.setImageResource(R.mipmap.dk_icon_sound_3);
    }

    class ViewHolder {
        private CheckBox choose_sentence_work_content;
        private TextView choose_senten_name_text;
        private ImageView word_audios_img;
    }
}
